package net.vinote.smart.platform.service.filter;


import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class WrapperRequest extends HttpServletRequestWrapper implements
		HttpServletRequest {

	private static final Pattern selfELPattern = Pattern
			.compile("\\$\\{session(\\.\\w+)+(})");
	private Map<String, String[]> params = new HashMap<String, String[]>();

	public WrapperRequest(ServletRequest httpServletRequest) {
		super((HttpServletRequest) httpServletRequest);
		this.params.putAll(httpServletRequest.getParameterMap());
	}

	/**
	 * 实现自定义表达式转义功能,若转义后获取的对象为null，则返回原表达式
	 * ${session.user}等价于session.getAttribute("user");
	 * ${session.user.id}等价于session.getAttribute("user").getId(); (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
	 */
	@Override
	public String getParameter(String name) {
		String[] values = params.get(name);
		if (values == null || values.length == 0)
			return null;
		String value = values[0];
		if (value != null && selfELPattern.matcher(value).matches()) {
			String[] attrArray = value.substring("${session.".length(),
					value.length() - 1).split("\\.");
			int attrLength = attrArray.length;
			if (attrLength > 0) {
				Object o = this.getSession().getAttribute(attrArray[0]);
				try {
					for (int i = 1; i < attrLength && o != null; i++) {
						String firstChar = attrArray[i].substring(0, 1);
						o = o.getClass()
								.getMethod(
										attrArray[i].replaceFirst(firstChar,
												"get" + firstChar.toUpperCase()))
								.invoke(o);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (o != null) {
					value = o.toString();
				}
			}
		}
		return value; 	
	}

}
